const db = require("../../config/db");

// 查所有企业
exports.getAllEnterprises = async (req, res) => {
    try {
        const [rows] = await db.query("SELECT * FROM enterprises");
        res.json(rows);
    } catch (err) {
        res.status(500).json({ message: "获取企业列表失败", error: err.message });
    }
};

// 根据id查企业
exports.getEnterpriseById = async (req, res) => {
    const { id } = req.params;

    try {
        const [rows] = await db.query("SELECT * FROM enterprises WHERE id = ?", [id]);
        if (rows.length === 0) {
            return res.status(404).json({ message: "企业未找到" });
        }
        res.json(rows[0]);
    } catch (err) {
        res.status(500).json({ message: "获取企业信息失败", error: err.message });
    }
};

// 新增企业
exports.createEnterprise = async (req, res) => {
    const {
      name,
      industry,
      credit_code,
      registered_capital,
      legal_person,
      address,
      establish_date,
    } = req.body;
  
    const connection = await db.getConnection(); // 获取数据库连接，支持事务
    try {
      await connection.beginTransaction();
  
      // 1️⃣ 插入企业信息
      const [enterpriseResult] = await connection.query(
        `INSERT INTO enterprises 
         (name, industry, credit_code, registered_capital, legal_person, address, establish_date)
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [name, industry, credit_code, registered_capital, legal_person, address, establish_date]
      );
  
      const enterpriseId = enterpriseResult.insertId;
  
      // 2️⃣ 初始化 relations 字段（包含结构但值为空）
      const defaultRelations = {
        upStreamJSON: [
          {
            legalPerson: "",
            enterpriseName: "",
            proportionEquity: null,
          },
        ],
        downStreamJSON: [
          {
            legalPerson: "",
            enterpriseName: "",
            proportionEquity: null,
          },
        ],
      };
  
      await connection.query(
        `INSERT INTO enterprise_relations (enterprise_id, relations) VALUES (?, ?)`,
        [enterpriseId, JSON.stringify(defaultRelations)]
      );
  
      await connection.commit();
  
      res.status(201).json({ message: "企业及其初始股权关系创建成功", id: enterpriseId });
    } catch (error) {
      await connection.rollback();
      console.error("新增企业失败:", error);
      res.status(500).json({ message: "企业创建失败", error: error.message });
    } finally {
      connection.release(); // 释放连接
    }
  };
  
  
  

// 删除企业
exports.deleteEnterprise = async (req, res) => {
    const { id } = req.params;

    try {
        // 先检查企业是否存在
        const [existing] = await db.query("SELECT * FROM enterprises WHERE id = ?", [id]);

        if (existing.length === 0) {
            return res.status(404).json({ message: "企业未找到" });
        }

        // 删除企业
        const [result] = await db.query("DELETE FROM enterprises WHERE id = ?", [id]);

        if (result.affectedRows > 0) {
            res.json({ message: "企业删除成功" });
        } else {
            res.status(500).json({ message: "删除失败，可能是数据库问题" });
        }
    } catch (err) {
        console.error("企业删除失败:", err);
        res.status(500).json({ message: "企业删除失败", error: err.message });
    }
};

// 更新企业信息
exports.updateEnterprise = async (req, res) => {
    const { id } = req.params;
    const { name, industry, credit_code, registered_capital, legal_person, address, establish_date } = req.body;

    try {
        // 检查企业是否存在
        const [existing] = await db.query("SELECT * FROM enterprises WHERE id = ?", [id]);

        if (existing.length === 0) {
            return res.status(404).json({ message: "企业未找到" });
        }

        // 更新企业信息
        const [result] = await db.query(
            "UPDATE enterprises SET name = ?, industry = ?, credit_code = ?, registered_capital = ?, legal_person = ?, address = ?, establish_date = ? WHERE id = ?",
            [name, industry, credit_code, registered_capital, legal_person, address, establish_date, id]
        );

        if (result.affectedRows > 0) {
            res.json({ message: "企业更新成功" });
        } else {
            res.status(500).json({ message: "更新失败，可能是数据库问题" });
        }
    } catch (err) {
        console.error("企业更新失败:", err);
        res.status(500).json({ message: "企业更新失败", error: err.message });
    }
};
